import useStore from "@/store/index";
const store = useStore();
import { errorNotify } from "@/utils/Misc";
export const Watermark = {
	async addWatermarkToImage(file) {
		try {
			const photographer = store?.user?.name || "未知拍摄人";
			const time = this.formatDateTime(new Date());
			const img = await this.fileToImage(file);
			const canvas = document.createElement("canvas");
			const ctx = canvas.getContext("2d");
			canvas.width = img.width;
			canvas.height = img.height;
			ctx.drawImage(img, 0, 0);
			this.drawCornerWatermark(ctx, canvas.width, canvas.height, {
				time,
				photographer,
			});
			return this.canvasToFile(canvas, file.name);
		} catch (error) {
			errorNotify("Watermark.js", "addWatermarkToImage", error);
			throw error;
		}
	},
	formatDateTime(date) {
		return date.toLocaleString("zh-CN", {
			year: "numeric",
			month: "2-digit",
			day: "2-digit",
			hour: "2-digit",
			minute: "2-digit",
			second: "2-digit",
		});
	},
	fileToImage(file) {
		return new Promise((resolve, reject) => {
			const img = new Image();
			img.onload = () => resolve(img);
			img.onerror = reject;
			img.src = URL.createObjectURL(file);
		});
	},
	drawCornerWatermark(ctx, width, height, info) {
		const padding = 30;
		const lineHeight = 35;
		const bgOpacity = 0.4;
		const textColor = "#ffffff";
		const fontSize = 24;
		const photographerText = `拍摄人: ${info.photographer}`;
		ctx.font = `${fontSize}px 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif`;
		const timeWidth = ctx.measureText(info.time).width;
		const photographerWidth = ctx.measureText(photographerText).width;
		const watermarkWidth = Math.max(timeWidth, photographerWidth) + 40;
		const watermarkHeight = lineHeight * 2;
		const x = width - watermarkWidth - padding;
		const y = height - watermarkHeight - padding;
		ctx.fillStyle = `rgba(0, 0, 0, ${bgOpacity})`;
		ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
		ctx.shadowBlur = 5;
		ctx.shadowOffsetX = 2;
		ctx.shadowOffsetY = 2;
		ctx.roundRect(x, y, watermarkWidth, watermarkHeight, 10);
		ctx.fill();
		ctx.shadowColor = "transparent";
		ctx.shadowBlur = 0;
		ctx.shadowOffsetX = 0;
		ctx.shadowOffsetY = 0;
		ctx.fillStyle = textColor;
		ctx.textBaseline = "top";
		ctx.fillText(info.time, x + 20, y + 10);
		ctx.fillText(photographerText, x + watermarkWidth - photographerWidth - 20, y + 5 + lineHeight);
	},
	canvasToFile(canvas, fileName) {
		return new Promise((resolve) => {
			canvas.toBlob((blob) => {
				const file = new File([blob], fileName, {
					type: blob.type || "image/jpeg",
					lastModified: Date.now(),
				});
				resolve(file);
			}, "image/jpeg");
		});
	},
};
